# usarrobot.py
# Creates a non-blocking socket connection and uses it to process 
# incoming messages.

import errno;
import socket;

import GameLogic;
import usarcore;
import usarmsg;

class Robot:
    def __init__(self):
        self._sock = None;
        self._buffer = "";
        self._init = None;

    def setClient(self, sock, buffer, init):
        self._sock = sock;
        self._sock.setblocking(0);
        self._buffer = buffer;
        self._init = init;

    def process(self):
        if not self._init:
            msgs = [];
        else:
            msgs = [self._init];
            self._init = None;
            
        if self._sock:
            try:
                line, self._buffer = \
                    usarmsg.readLine(self._sock, self._buffer);
                while line:
                    msg = usarmsg.parseLine(line);
                    if msg:
                        msgs.append(msg);
                    line, self._buffer = \
                        usarmsg.readLine(self._sock, self._buffer);
            except socket.error, e:
                self._sock.close();
                self._sock = None;
                if e[0] != errno.EPIPE:
                    raise;

        return msgs;

    def send(self, msg):
        msglen = len(msg);
        totalsent = 0;
        if self._sock:
            while (totalsent < msglen):
                submsg = buffer(msg, totalsent, msglen - totalsent);
                try:
                    sent = self._sock.send(submsg);
                except socket.error, e:
                    if e[0] == errno.EAGAIN:
                        sent = 0;
                    else:
                        self._sock.close();
                        self._sock = None;
                        if e[0] == errno.EPIPE:
                            return;
                        else:
                            raise;
                totalsent += sent;
